package com.wave2.shadow.dao;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import com.wave2.shadow.exceptions.UserAlreadyExists;
import com.wave2.shadow.model.JoinForm;
import com.wave2.shadow.persistence.Contacts;

@Repository("registrationDao")
@TransactionConfiguration(transactionManager = "transactionManager")
@Transactional
public class RegistrationDaoImpl implements RegistrationDao {

	@Autowired
	public SessionFactory sessionFactory;

	/* (non-Javadoc)
	 * @see com.wave2.shadow.dao.RegistrationDao#addUser(com.wave2.shadow.controller.JoinForm)
	 */
	@Override
	public void addUser(JoinForm form) throws UserAlreadyExists {
		Session sess = null;

		sess = sessionFactory.getCurrentSession();

		// Search DB to find if there is already an entry for the user trying to
		// be added.
		Criteria crit = sess.createCriteria(Contacts.class).add(
				Restrictions.eq("email", form.getEmail()));

		@SuppressWarnings("unchecked")
		List<Contacts> list = crit.list();

		if (list.isEmpty()) {
			Contacts user = new Contacts();
			user.setEmail(form.getEmail());
			user.setFirstname(form.getFirstName());
			user.setLastname(form.getLastName());
			user.setPhone1(form.getPhonenumber());
			user.setPass(form.getPassword());

			sess.save(user);
		} else {
			throw new UserAlreadyExists(form.getEmail());
		}

	}

	/* (non-Javadoc)
	 * @see com.wave2.shadow.dao.RegistrationDao#getUser()
	 */
	@Override
	public List<Contacts> getUser() {
		Session sess = null;

		sess = sessionFactory.getCurrentSession();
		Query q = sess.createQuery("FROM Contacts");

		@SuppressWarnings("unchecked")
		List<Contacts> lst = q.list();

		return lst;
	}
}
